package com.webull.information.center.carwler.job.branch;

import java.util.List;
import java.util.Optional;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import com.webull.information.center.carwler.common.util.CarwlerJobStateUtil;
import com.webull.information.center.carwler.dao.CarwlerNewsDao;

/**
 * 各分支删除被base已处理过的记录
 */
@Component
public class Branch_Process_Past_Job implements SimpleJob {
    protected final Logger logger = LogManager.getLogger(getClass());
	private @Autowired CarwlerJobStateUtil carwlerJobStateUtil;
	private @Autowired CarwlerNewsDao carwlerNewsDao;


	@Override
	public void execute(ShardingContext context) {
		int sharding = Optional.ofNullable(context).map(v -> v.getShardingItem()).orElse(-1);
		int totalCount = Optional.ofNullable(context).map(v -> v.getShardingTotalCount()).orElse(-1);

		carwlerJobStateUtil.assertCarwlerJobConfig(false);

		logger.info("branch_Process_Past_Job start:" + ArrayUtils.toString(sharding) + ",totalCount:" + totalCount);

		processBaseRel();

		processBranchNews();
	}

    private void processBranchNews() {
        try {
            Integer lastId = carwlerJobStateUtil.getPastNewsIdByCarwler();
            final String tabName = carwlerJobStateUtil.getEdenNewsTable();
            logger.info("branch_Process_Past_Job.processBranchNews start carwler{}  ,lastId:{} ", tabName, lastId);

            int res = 0;
            while0:
            while (true) {
                int res0 = deleteCarwlerRecord(tabName, lastId);
                if (res0 <= 0) break while0;
                res += res0;
            }
            if (res <= 0) return;

//            CollectRecord record = backRecord();
//            record.setExchangeCode(tabName);
//            record.setExchangeId(-1);
//            record.setLastTickerId(lastId);
//            Integer collId = collectRecordDao.add(record);
            logger.info("branch_Process_Past_Job.processBranchNews end tabName{} div ,carwler:{},res{}",
                    tabName, lastId, res);
        } catch (Exception e) {
            logger.error("branch_Process_Past_Job.processBranchNews collectJob div error:", e);
        }
    }

    private void processBaseRel() {
        try {
            Integer lastId = carwlerJobStateUtil.getPastBaRelIdByCarwler();
            final String tabName = carwlerJobStateUtil.getBaseRelTable();
            logger.info("branch_Process_Past_Job.processBaseRel start carwler{}  ,lastId:{} ", tabName, lastId);

            int res = 0;
            while0:
            while (true) {
                int res0 = deleteCarwlerRecord(tabName, lastId);
                if (res0 <= 0) break while0;
                res += res0;
            }
            if (res <= 0) return;

//            CollectRecord record = backRecord();
//            record.setExchangeCode(tabName);
//            record.setExchangeId(-1);
//            record.setLastTickerId(lastId);
//            Integer collId = collectRecordDao.add(record);
            logger.info("branch_Process_Past_Job.processBaseRel end tabName{} div ,carwler:{},res{}",
                    tabName, lastId, res);
        } catch (Exception e) {
            logger.error("branch_Process_Past_Job.processBaseRel collectJob div error:", e);
        }
    }


    private int deleteCarwlerRecord(String tabName, Integer lastId) {

        List<Integer> ids = carwlerNewsDao.selectCarwlerRecord(tabName, lastId);
        if (ids == null || ids.isEmpty()) return 0;
        int res = 0;
        for (Integer id : ids) {
            int recored = carwlerNewsDao.deleteCarwlerRecord(tabName, id);
            res += recored;
        }
        return res;
    }


}
